package com.andnux.android.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewbinding.ViewBinding;

import com.andnux.android.network.IReceiveMessage;
import com.andnux.android.network.WebSocketManager;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public class BaseActivity<T extends ViewBinding> extends AppCompatActivity implements IReceiveMessage {

    protected T binding;
    private CompositeDisposable compositeDisposable;

    @Override
    @SuppressWarnings("all")
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        compositeDisposable = new CompositeDisposable();
        try {
            ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
            Class<T> aClass = (Class<T>) type.getActualTypeArguments()[0];
            Method method = aClass.getDeclaredMethod("inflate", LayoutInflater.class);
            binding = (T) method.invoke(null, LayoutInflater.from(this));
            setContentView(binding.getRoot());
            WebSocketManager.getInstance().setReceiveMessage(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addDisposable(Disposable disposable) {
        compositeDisposable.add(disposable);
    }

    @Override
    protected void onDestroy() {
        if (binding != null) {
            binding = null;
        }
        if (compositeDisposable != null) {
            compositeDisposable.dispose();
        }
        super.onDestroy();
    }

    @Override
    public void onConnectSuccess() {

    }

    @Override
    public void onConnectFailed() {

    }

    @Override
    public void onClose() {

    }

    @Override
    public void onMessage(String text) {
        Intent intent = new Intent("message");
        sendBroadcast(intent);
    }
}
